package client.comm.baoding.fragment

import android.view.View
import client.comm.commlib.base.BaseFragment
import client.comm.commlib.comm_ui.draw.SpaceItemDecoration
import client.comm.commlib.widget.EmptyLayout
import client.comm.baoding.R
import client.comm.baoding.adapter.TdAdapter
import client.comm.baoding.api.bean.TdBean
import client.comm.baoding.databinding.FragmentTdBinding
import client.comm.baoding.ui.vm.MainViewModel

class TdFragment : BaseFragment<FragmentTdBinding, MainViewModel>() {

    override fun getViewId(): Int {
        return R.layout.fragment_td
    }

    override fun initViewModel(): MainViewModel = createViewModel()
    val adapter: TdAdapter by lazy {
        TdAdapter(requireActivity(), mImgLoader)
    }

    override fun initWidget() {
        binding.recyclerView.adapter = adapter
        binding.recyclerView.addItemDecoration(SpaceItemDecoration(10))
        binding.refreshLayout.setOnRefreshListener {
            viewModel.pageOne.value = 0
            viewModel.get_user_team()
        }
        binding.emptyLayout.setOnClickListener {
            viewModel.userInfo()
        }

        viewModel.callTd.observe(this, {
            it?.let {
                if (it.isSuccess) {
                    if (viewModel.callOne.value == null) {
                        viewModel.pageOne.value = 0
                        viewModel.get_user_team()
                    }
                }
            }
        })

        viewModel.callOne.observe(this, {
            it?.let {
                if (it.isSuccess) {
                    val list = ArrayList<TdBean.Sub?>()
                    list.addAll(it.data!!.sub_list)
                    adapter.submitData(list, it.data!!)
                    if (list == null || list.size < 10) {
                        adapter.hasMoreState.value = false
                    }

                    binding.emptyLayout.visibility = View.GONE
                } else {
                    binding.emptyLayout.errorType = EmptyLayout.NETWORK_ERROR
                }
                binding.refreshLayout.isRefreshing = false
            }
        })
    }

    override fun initData() {
        if (viewModel.callOne.value == null) {
            if (viewModel.callTd.value == null) {
                viewModel.userInfo()
            } else {
                viewModel.pageOne.value = 0
                viewModel.get_user_team()
            }
        }
    }

}